<?php
namespace src\logic;
use \classlib\core as C;
class lstudio {
	const LISTSIZE 			= 25;
	const TIMERANGE 		= 300;
	static $iscasual_starlv = array(1, 4);
	
	//验证一个等级是否是签约主播
	public static function grade($starlv) {
		return ($starlv != 4)? 1:0;
	}
	
	//获取直播间开通唯一识别码
	public static function domain() {
		$domain = C\rand_str(8, 2);
		$sorm   = C\model::load('pro.pl.studio');
		do {
			$sid = $sorm->isexist(array('studiono'=>$domain));
			if (!$sid) {
				break;
			}
			$domain = C\rand_str(8, 2);
		}while(true);
		return $domain;
	}
	
	//开通直播间
	public static function open($userid, $user, $star='C') {
		$domain = self::domain();
		$star   = C\model::load('pro.inc.star')->get_item(array('star'=>$star));
		$starlv = empty($star)? 4:$star['id'];
		//创建直播间 默认略质主播
		$fields = array('userid'=>$userid, 'author'=>$user['nickname'], 'studiono'=>$domain, 'isjoin'=>0,
			'starlv'=>$starlv, 'iscasual'=>1, 'lv'=>$user['lv'], 'exp'=>$user['exp'], 'status'=>1, 'title'=>$title,
			'jointime'=>C\config::$nowtime, 'isshow'=>0, 'origin'=>0, 'isvod'=>0, 'stime'=>C\config::$nowtime);
		$fields['id'] = C\model::load('pro.pl.studio')->new_one($fields);
		C\model::load('pro.pl.userinfo')->set_dev($userid)->save($userid, array('isanchor'=>1));
		return $fields;
	}
	
	/**
	 * 时间语言包的替换提示语
	 * @param unknown $aritme
	 * @param unknown $isschedule
	 * @param unknown $translate
	 * @return string|unknown
	 */
	public static function aritime($aritme, $isschedule, &$translate) {
		$strtime = '';
		if ($aritme < 60) {
			$strtime = ($isschedule == 1)? $translate['nowonlive']:$translate['nowofflive'];
		} else if ($aritme < 3600) {
			$lang    = ($isschedule == 1)? $translate['minonlive']:$translate['minofflive'];
			$strtime = sprintf($lang, ceil($aritme / 60));
		} else if ($aritme < 86400) {
			$lang    = ($isschedule == 1)? $translate['houronlive']:$translate['hourofflive'];
			$strtime = sprintf($lang, ceil($aritme / 3600));
		} else {
			$ndays   = ceil($aritme / 86400);
			if ($ndays > 7) {
				$ndays = 7;
			}
			$lang    = ($isschedule == 1)? $translate['dayonlive']:$translate['dayofflive'];
			$strtime = sprintf($lang, $ndays);
		}
		return $strtime;
	}
	
	/**
	 * 判断是否可以修改主播等级(1、90天周期已过 2、当前周期播放时间是0 才允许修改等级、重置周期时间起点【开始新的90天周期】)
	 * @param int $starlv
	 */
	public static function updateGrade($userid, $starlv) {
		$aorm   = C\model::load('pro.pl.anchor');
		$anchor = $aorm->get_one($userid);
		if ($anchor['starlv'] == $starlv) {
			return true;
		}
		$cycle  = $anchor['jointime'] + 24 * 3600 * 90;
		if (C\config::$nowtime < $cycle && !in_array($anchor['starlv'], self::$iscasual_starlv)) {
			$day30time = 24 * 3600 * 30;
			//判断主播所在哪个周期
			$where = array('userid'=>$userid);
			$endtime  = C\model::load('pro.pl.salary')->get_value('endtime', $where, 'id', \classlib\orm::DESC);
			$start    = ($endtime > $anchor['jointime']) ? $endtime : $anchor['jointime'];
			$end   = $start + $day30time;
			//判断这个周期播放时间是否为0
			$where = array('userid'=>$userid, array('offtime', $start, \classlib\orm::OP_GE), array('offtime', $end, \classlib\orm::OP_LT));
			$time  = C\model::load('pro.pl.event')->set_dev($userid)->get_total($where, 'SUM(lasttime - aritime)');
			if ($time) {
				return false;
			}
		}
		$field = array('starlv'=>$starlv, 'jointime'=>C\config::$nowtime);
		$aorm->save($userid, $field);
		if (self::grade($starlv)) {
			$field = array('iscasual'=>0, 'isrecommend'=>C\config::$nowtime);
			$sorm = C\model::load('pro.pl.studio');
			$sid  = $sorm->get_value('id', array('userid'=>$userid));
			$sorm->save($sid, $field);
		}
		return true;
	}

	/**
	 * 验证是否需要已经开播设置过了
	 * @param array $studio
	 * @return boolean
	 */
	public static function isplayset($studio) {
		if ($studio['olstatus'] == 1) {
			return true;
		}
		if (abs(C\config::$nowtime - $studio['airtime']) < self::TIMERANGE) {
			return true;//预约时间达到了直接进入
		}
		if ($studio['isset'] && abs(C\config::$nowtime - $studio['stime']) < self::TIMERANGE) {
			return true;//已经完成了开播设置了
		}
		if (abs(C\config::$nowtime - $studio['lasttime']) < self::TIMERANGE) {
			return true;//已经完成了开播设置了
		}
		return false;
	}
	
	//开启直播通道信息
	public static function broadcast($tools, &$studio) {
		if ($studio['olstatus'] == 1 && $studio['eventid'] > 0) {//如果状态是在线的需要将前一个场次关闭
			$eorm = C\model::load('pro.pl.event')->set_dev($studio['id']);
			$eorm->save($evtid, array('offtime'=>C\config::$nowtime));
		}
		//随机初始化Token
		$studio['ptocken'] = C\rand_str(8, 2);
		$studio['rtocken'] = C\rand_str(8, 2);
		//更新直播间信息
		$field = array('ptocken'=>$studio['ptocken'], 'rtocken'=>$studio['rtocken'], 'isset'=>0, 'olstatus'=>1,
			'isshow'=>1, 'lasttime'=>C\config::$nowtime,  'oltools'=>$tools, 'neartime'=>C\config::$nowtime);
		if ($studio['isjoin'] == 0) {
			$field['isjoin']  	= 1;
			$field['jointime']  = C\config::$nowtime;
		}
		$user   = C\model::load('pro.pl.userinfo')->set_dev($studio['userid'])->get_one($studio['userid']);
		$field['eventid'] = levent::create($studio, $user);
		$field['rtmp']    = lrtmp::push($studio['ptocken'], $tools, $studio['id'], $studio['userid'], $field['eventid']);
		C\model::load('pro.pl.studio')->save($studio['id'], $field);
		//开播状态IM要广播出去...
		$hash    = md5($studio['ptocken'].$studio['rtocken']);
		limapi::notifystudio($studio['id'], $hash, $studio['userid'], 20020);
		//发送开播通知广播
		limapi::notifystatus($studio['id'], $studio['userid'], $studio['rtocken'], 1, $field['eventid']);
		limapi::notifystart($user, $studio);
		lrobots::add($studio['id']);
		return array('evtid'=>$field['eventid'], 'rtmp'=>$field['rtmp']);
	}
	
	//处理主播状态数据上报的处理逻辑
	public static function dostatus($evtid, $status, &$studio) {
		$olmax  = limapi::getolbyid($studio['id']);
		$eorm   = C\model::load('pro.pl.event')->set_dev($studio['id']);
		$evnt   = $eorm->get_one($evtid);
		$field  = array('lasttime'=>C\config::$nowtime);
		($olmax > $evnt['olmax']) && $field['olmax'] = $olmax;
		if ($status == 1) {/*开始本次直播提交的数据信息*/
			$eorm->save($evtid, $field);
		} else {/*结束直播上报的状态信息*/
			$field['offtime'] = C\config::$nowtime;
			$eorm->save($evtid, $field);
			$field  = array('olstatus'=>0, 'eventid'=>0, 'lasttime'=>C\config::$nowtime);
			C\model::load('pro.pl.studio')->save($studio['id'], $field);
			limapi::notifystatus($studio['id'], $studio['userid'], $studio['rtocken'], 0, 0);
			lrobots::del($studio['id']);//促发删除机器人
		}		
	}
	
	/**
	 * 获取首页展示的直播间开播设置信息
	 * @param unknown $userid
	 * @param unknown $loginpw
	 * @return array
	 */
	public static function item($userid, $loginpw) {
		$studio = self::get($userid);
		if ($studio) {
			$studio['isplayset'] = self::isplayset($studio);
			$studio['sign']      = ltoken::pc($userid, $studio['id'], $loginpw);
			$studio['link']      = C\router::get_url('live', $studio['studiono']);
		}
		return $studio;
	}
	
	//获取直播间信息
	public static function get($userid, $status=1) {
		$where  = array('userid'=>$userid);
		if ($status > -1) {
			$where['status'] = $status;
		}
		$studio = C\model::load('pro.pl.studio')->get_item($where);
		return $studio;
	}
	
	//验证开播设置
	public static function setting($userid) {
		$studio = self::get($userid, -1);
		if (!$studio) { //验证邮箱是否验证通过了
			$user = C\model::load('pro.pl.userinfo')->set_dev($userid)->get_one($userid);
			if (!$user['emailverify']) {
				ob_end_clean();
				return '80114';
			}
			$studio = array('tags'=>array(), 'title'=>'', 'mshare'=>0, 'id'=>0, 'airtime'=>0);
		} else {
			if ($studio['status'] != 1) { //直播间被禁用掉了
				ob_end_clean();
				return '80115';
			}
			$studio['tags'] = @explode(',', $studio['tags']);
		}
		return $studio;
	}
	
	/**
	 * 获取首页数据信息
	 * @param number $tagid
	 * @param string $rank
	 * @param array  $filterids
	 * @param number $userid
	 * @param number $filterme
	 * @param number $start
	 * @param number $limit
	 * @return array $list;
	 */
	public static function home($tagid, $rank, $filterids=array(), $userid=0, $filterme=0, $start=0, $limit=10) {
		if ($limit < 1 || $limit > self::LISTSIZE) {
			$limit = self::LISTSIZE;
		}
		//获取一定订阅的资料信息
		$feed  = ($userid > 0)? luser::myfeed($userid):array();
		$field = 'id,userid,olstatus,airtime,title,viewer,tags,realuser,studiono,thumb,starlv,lv,exp';
		$where = array('status'=>1, array('isshow', 0, \classlib\orm::OP_NE));
		$sorts = array();
		if ($rank == 'new') { //最新开播
			$where['olstatus']   = 1;
			$sorts['neartime']   = \classlib\orm::DESC;
			$sorts['viewer']     = \classlib\orm::DESC;
			$sorts['id']         = \classlib\orm::ASC;
		} else if ($rank == 'soon') { //即将开播的数据
			$where[] = array('airtime', C\config::$nowtime, \classlib\orm::OP_GT);
			if ($filterme) {
				$where[] = array('userid', $userid, \classlib\orm::OP_EQ);
			}
			$sorts['airtime']    = \classlib\orm::ASC;
			$sorts['exp']        = \classlib\orm::DESC;
			$sorts['id']         = \classlib\orm::ASC;
		} else { //默认首页的热门数据
			$where[] = array('(');
			$where[] = array('olstatus', 1, \classlib\orm::OP_EQ);
			$where[] = array('isvod', 1, \classlib\orm::OP_EQ, \classlib\orm::OP_OR);
			$where[] = array(')');
			$field  .= ',if((olstatus <> 1 && (cast(airtime as SIGNED)-UNIX_TIMESTAMP()) > 0), 1, 0) as alstatus,'.
				'if((starlv = 4), 0, 1) as iscurated';
			$sorts['olstatus']   = \classlib\orm::DESC; //在线
			$sorts['alstatus']   = \classlib\orm::DESC; //预约
			$sorts['iscurated']  = \classlib\orm::DESC; //等级类别
			$sorts['viewer']     = \classlib\orm::DESC; //观众
		}
		//通过拼凑SQL的方式执行 标签赛选
		if ($tagid > 0) {
			$table   = C\model::load('pro.pl.sttag')->set_mod($tagid)->get_table();
			$sql     = sprintf('id in(select sid from %s where tagid=%d);', $table, $tagid);
			$where[] = array($sql, \classlib\orm::OP_SQL);
		}
		if (!empty($filterids)) {
			$where[] = array('id', $filterids, \classlib\orm::OP_NOTIN);
			$start   = 0;
		}
		//遍历获取直播间的数据资料
		$list  = C\model::load('pro.pl.studio')->get_list($start, $limit, $where, $field, $sorts);
		$uorm  = C\model::load('pro.pl.userinfo');
		foreach ($list as &$item) {
			$user  = $uorm->set_dev($item['userid'])->get_one($item['userid']);
			$item['nickname'] = $user['nickname'];
			$item['avtar']    = $user['thumb'];
			$item['lvicon']   = lv::icon($user['lv'], 0);
			$item['link']     = C\router::get_url('live', $item['studiono']);
			$item['tags']     = ltags::stags($item['tags']);
			($item['airtime'] < C\config::$nowtime) && $item['airtime'] = 0;
			($rank == 'soon') && $item['olstatus'] = 0;
			$item['feed']     = isset($feed[$item['id']]);
			$item['starlv']   = self::grade($item['starlv']);
			$item['viewer']   = $item['viewer'] + $item['realuser'];
			unset($item['realuser']);
		}
		return $list;
	}
	
	//获取我关注的直播间列表
	public static function myfollow($userid, $tagid, $filterids=array(), $start=0, $limit=10) {
		$list   = array();
		$fansid = luser::myfocus($userid);
		if (empty($fansid)) {
			return $list;
		}
		if ($limit < 1 || $limit > self::LISTSIZE) {
			$limit = self::LISTSIZE;
		}
		$where = array(array('userid', $fansid, \classlib\orm::OP_IN), 
			array('isshow', 0, \classlib\orm::OP_NE), 'status'=>1);
		//通过拼凑SQL的方式执行 标签赛选
		if ($tagid > 0) {
			$table   = C\model::load('pro.pl.sttag')->set_mod($tagid)->get_table();
			$sql     = sprintf('id in(select sid from %s where tagid=%d);', $table, $tagid);
			$where[] = array($sql, \classlib\orm::OP_SQL);
		}
		if (!empty($filterids)) {
			$where[] = array('id', $filterids, \classlib\orm::OP_NOTIN);
			$start   = 0;
		}
		$feed  = luser::myfeed($userid);
		$sorts = array('olstatus'=>\classlib\orm::DESC, 'viewer'=>\classlib\orm::DESC);
		$field = 'id,userid,olstatus,airtime,title,viewer,tags,realuser,studiono,thumb,starlv,lv,exp';
		$list  = C\model::load('pro.pl.studio')->get_list($start, $limit, $where, $field, $sorts);
		$uorm  = C\model::load('pro.pl.userinfo');
		foreach ($list as &$item) {
			$user  = $uorm->set_dev($item['userid'])->get_one($item['userid']);
			$item['nickname'] = $user['nickname'];
			$item['avtar']    = $user['thumb'];
			$item['lvicon']   = lv::icon($user['lv'], 0);
			$item['link']     = C\router::get_url('live', $item['studiono']);
			$item['tags']     = ltags::stags($item['tags']);
			($item['airtime'] < C\config::$nowtime) && $item['airtime'] = 0;
			$item['feed']     = isset($feed[$item['id']]);
			$item['starlv']   = self::grade($item['starlv']);
			$item['viewer']   = $item['viewer'] + $item['realuser'];
			unset($item['realuser']);
		}
		return $list;
	}
	
	//获取推荐的信息列表
	public static function recommend($userid, $start=0, $limit=5) {
		$where = array(array('isrecommend', 0, \classlib\orm::OP_NE), 'status'=>1);
		$sorts = array('olstatus'=>\classlib\orm::DESC, 'xfans'=>\classlib\orm::DESC);
		$field = 'id,userid,olstatus,airtime,title,viewer,tags,realuser,studiono,thumb,starlv,xfans,lv,exp';
		$list  = C\model::load('pro.pl.studio')->get_list($start, $limit, $where, $field, $sorts);
		$uorm  = C\model::load('pro.pl.userinfo');
		$myfocus = ($userid > 0)? luser::myfocus($userid):array();
		foreach ($list as &$item) {
			$user  = $uorm->set_dev($item['userid'])->get_one($item['userid']);
			$item['nickname'] = $user['nickname'];
			$item['avtar']    = $user['thumb'];
			$item['lvicon']   = lv::icon($user['lv'], 0);
			$item['link']     = C\router::get_url('index', 'linkto', array('sid'=>$item['id']));
			$item['tags']     = ltags::stags($item['tags']);
			($item['airtime'] < C\config::$nowtime) && $item['airtime'] = 0;
			$item['feed']     = isset($feed[$item['id']]);
			$item['starlv']   = self::grade($item['starlv']);
			$item['viewer']   = $item['viewer'] + $item['realuser'];
			$item['isfan']    = in_array($item['userid'], $myfocus)? 1:0;
			unset($item['realuser']);
		}
		return $list;
	}
	
	//首页随机获取一个主播
	public static function rand($userid, $id) {
		$data   = array();
		$field  = 'id,userid,olstatus,airtime,title,viewer,tags,realuser,studiono,thumb,starlv,lv,exp';
		$where  = array('status'=>1, 'id'=>array($id, \classlib\orm::OP_NE));
		$sort   = array('olstatus'=>\classlib\orm::DESC, 'isrecommend'=>\classlib\orm::DESC, 'lasttime'=>\classlib\orm::DESC);
		$sorm   = C\model::load('pro.pl.studio');
		$studio = $sorm->get_item($where, $field, $sort);
		if (!$studio || !$studio['olstatus']) {//记录不存在或者状态不正确重新取一次数据
			unset($where['id']);
			$studio = $sorm->get_item($where, $field, $sort);
		}
		if (!$studio) {//不存在返回空的数组
			return $data;
		}
		$user   = C\model::load('pro.pl.userinfo')->set_dev($studio['userid'])->get_one($studio['userid']);
		$evtid  = levent::geteid($studio['id'], $studio['userid']);
		$rtmp   = array(lrtmp::recv($studio['rtocken'], $studio['id'], $studio['userid'], $evtid));
		$myfeed = luser::myfeed($userid, $studio['id']);
		($studio['airtime'] < C\config::$nowtime) && $studio['airtime'] = 0;
		$studio['tags'] = ltags::stags($studio['tags']);
		$studio['link'] = C\router::get_url('live', $studio['studiono']);
		$studio['feed']   = empty($myfeed)? 0:1;
		$studio['viewer'] = $studio['viewer'] + $studio['realuser'];
		$studio['thumb']  = lshare::uri().$studio['thumb'];
		$studio['rtmp']   = $rtmp;
		$studio['avtar']  = lshare::uri().$user['thumb'];
		$studio['nickname']  = $user['nickname'];
		$studio['lvicon'] = lv::icon($user['lv'], 0);
		$studio['starlv'] = self::grade($item['starlv']);
		return $studio;
	}
}

